<template>
  <div class="external-treatment-container">
    <!-- 中药处方二 -->
    <div class="custom-table external-treatment-prescription">
      <!-- 标题栏 -->
      <div class="table-header" style="justify-content: space-between">
        <div style="display: flex; align-items: center">
          <div
            class="header-cell"
            style="width: 100px; color: #000000; font-weight: 600"
          >
            {{ externalTreatment.rxName }}
          </div>
          <!-- <div style="margin-left: 10px">
            <el-select
              v-model="externalTreatment.storageId"
              style="width: 140px"
              class="borderless-select"
              :disabled="visitStatus === '2'"
            >
              <el-option
                v-for="frequency in storageList"
                :key="frequency.storageName"
                :label="frequency.storageName"
                :value="frequency.storageId"
              />
            </el-select>
          </div> -->
        </div>
        <!-- <div class="header-cell" v-if="visitStatus !== '2'">
          <span style="color: #e37318; margin-right: 10px"
            >费用：￥{{
              (externalTreatment.totalAmount / 100).toFixed(2)
            }}</span
          >
          <div
            class="header-cell"
            @click="removeRow_1(externalTreatment.tcmInfo.detailList)"
          >
            <img src="@/assets/manage/icon_del_nor.svg" alt="" />
          </div>
        </div> -->
        <div
          v-if="visitStatus !== '2'"
          class="header-cell"
          @click="removeRow_1(externalTreatment.tcmInfo.detailList)"
        >
          <img src="@/assets/manage/icon_del_nor.svg" alt="" />
        </div>
      </div>

      <!-- 处方选择行 -->
      <div class="prescription-form-row">
        <div class="form-item">
          <!-- <el-select
            v-model="externalTreatment.tcmInfo.frequencyCode"
            style="width: 120px"
            class="borderless-select borderless-select_1"
            :suffix-icon="CaretBottom"
            placeholder="请选择频次"
            @change="onFrequency(externalTreatment.tcmInfo)"
            filterable
            clearable
            v-if="visitStatus !== '2'"
          >
            <el-option
              v-for="item in FREQUENCY"
              :key="item.frequencyCode"
              :label="item.frequencyName"
              :value="item.frequencyCode"
            />
          </el-select> -->
          <el-select
            v-model="externalTreatment.tcmInfo.frequencyCode"
            style="width: 120px"
            filterable
            clearable
            class="borderless-select borderless-select_1"
            :suffix-icon="CaretBottom"
            placeholder="请选择频次"
            @change="onFrequency(externalTreatment.tcmInfo)"
            v-if="visitStatus !== '2'"
          >
            <el-option
              v-for="frequency in FREQUENCY"
              :key="frequency.frequencyCode"
              :label="frequency.frequencyName"
              :value="frequency.frequencyCode"
              style="padding: 0 8px"
            >
              <span style="float: left">{{ frequency.frequencyCode }}</span>
              <span style="float: right; font-size: 13px">
                {{ frequency.frequencyName }}
              </span>
            </el-option>
          </el-select>
          <span v-else>
            {{ externalTreatment.tcmInfo.frequencyCodeText }}
          </span>
        </div>
        <div class="form-item">
          <el-select
            v-model="externalTreatment.tcmInfo.dailyDosage"
            style="width: 100px"
            class="borderless-select borderless-select_1"
            :suffix-icon="CaretBottom"
            placeholder=""
            filterable
            v-if="visitStatus !== '2'"
          >
            <el-option
              v-for="item in tcmDailyDosageEnum"
              :key="item.value"
              :label="item.text"
              :value="item.value"
            />
          </el-select>
          <span v-else>
               {{
              useBaseDataStores.getEnumData(
                externalTreatment.tcmInfo.dailyDosage,
                'tcmDailyDosageEnum'
              )
            }}
          </span>
        </div>
        <div
          style="
            display: flex;
            align-items: center;
            gap: 8px;
            position: relative;
          "
        >
          <el-input-number
            v-model="externalTreatment.tcmInfo.cycle"
            :min="0"
            :max="999"
            :controls="false"
            class="borderless-input"
            style="width: 50px"
            @change="
              updateRow(
                externalTreatment.tcmInfo,
                externalTreatment.tcmInfo.uuid
              )
            "
            @focus="
              showKeyboard(
                externalTreatment.tcmInfo,
                externalTreatment.tcmInfo.uuid,
                'cycle'
              )
            "
            @click.stop
            v-if="visitStatus !== '2'"
          />
          <span v-else>{{ externalTreatment.tcmInfo.cycle }}</span>
          <span>{{ externalTreatment.tcmInfo.cycleUnitText }} </span>
          <div
            v-if="
              keyboardVisible &&
              currentEditNum === externalTreatment.tcmInfo.uuid &&
              currentEditField === 'cycle'
            "
            class="number-keyboard"
            @click.stop
          >
            <NumericKeyboardInt @input="inputNumber" @delete="deleteNumber" />
          </div>
        </div>
        <div class="form-item">
          <div
            class="table-cell"
            @click.stop="onUsageCode('1')"
            v-if="visitStatus !== '2'"
            style="
              position: relative;
              min-width: 56px;
              height: 36px;
              line-height: 36px;
              background: rgba(220, 220, 220, 0.1);
              border-radius: 6px 6px 6px 6px;
              border: 1px solid #ebebeb;
              font-size: 13px;
              text-align: center;
              padding: 0 5px;
            "
          >
            {{ externalTreatment.tcmInfo.usageCodeText }}
            <!-- <el-icon size="14" style="margin-left: 25px;"><CaretBottom /></el-icon> -->
            <div
              v-if="showMedicationTabs && currentUsageRow === '1'"
              @click.stop
              style="position: absolute; top: 30px; left: 0; z-index: 10"
            >
              <MedicationTabs @select="selectedUsage" :rxType="3" />
              <!-- <HerbUsagePopup
                @onUsageClick="
                  (result) => selectedUsage(result, externalTreatment.tcmInfo)
                "
              >
              </HerbUsagePopup> -->
            </div>
          </div>
          <div
            class="table-cell"
            v-else
            style="
              position: relative;
              width: 56px;
              height: 36px;
              line-height: 36px;
              border-radius: 6px 6px 6px 6px;
              text-align: center;
            "
          >
            {{ externalTreatment.tcmInfo.usageCodeText }}
          </div>
        </div>
        <div class="form-item">
          <div
            class="table-cell"
            style="width: 50px; justify-content: flex-start; padding-left: 8px"
          >
            1次
          </div>
          <div class="table-cell">
            <div
              @click.stop="onUsageDosage('2')"
              v-if="visitStatus !== '2'"
              style="
                width: 56px;
                height: 36px;
                line-height: 36px;
                background: rgba(220, 220, 220, 0.1);
                border-radius: 6px 6px 6px 6px;
                border: 1px solid #ebebeb;
                justify-content: flex-start;
                font-size: 13px;
                text-align: center;
                position: relative;
              "
            >
              {{ externalTreatment.tcmInfo.singleDosage }} ml
              <div
                @click.stop
                v-if="showMedicationDosage && currentUsageRow === '2'"
                style="position: absolute; top: 30px; left: 0; z-index: 10"
              >
                <Dosage @selectItem="onSelectItem" />
              </div>
            </div>
            <div
              v-else
              style="
                width: 56px;
                height: 36px;
                line-height: 36px;
                justify-content: flex-start;
                text-align: center;
                position: relative;
              "
            >
              {{ externalTreatment.tcmInfo.singleDosage }} ml
            </div>
          </div>
        </div>

        <div class="form-item">
          <AutocompleteMulti
            v-model="externalTreatment.tcmInfo.remark"
            class="right-select"
            placeholder="备注"
            style="width: 220px"
            :trigger-on-focus="true"
            :fetch-suggestions="querySearchAsync"
            :selected-color="'#16ada4'"
            v-if="visitStatus !== '2'"
          />
          <span v-else>{{ externalTreatment.tcmInfo.remark }}</span>
        </div>
      </div>

      <!-- 穴位选择区域 -->
      <div class="acupoint-selection-area">
        <div class="acupoint-row">
          <!-- 左侧组合选择框 -->
          <div
            class="combined-select-group"
            v-for="(item, index) in externalTreatment.tcmInfo.detailList"
            :key="index"
          >
            <div style="position: relative">
              <el-input
                v-model="item.drugName"
                :style="{ width: calcInputWidth(item.drugName) }"
                class="borderless-select left-select"
                placeholder=""
                type=""
                @input="handleSearch_1"
                @focus="showSearchKeyboard_1(item.uuid)"
                @click.stop
                :disabled="visitStatus == '2'"
              >
              </el-input>
              <!-- <el-icon size="14"><CaretBottom /></el-icon> -->
              <div
                style=""
                class="combined-select-group-1"
                @click.stop="onUsage(item.uuid)"
                v-if="visitStatus != '2'"
              >
                <span v-if="item.decotionMethod">
                  {{
                    useBaseDataStores.getEnumData(
                      item.decotionMethod,
                      'decotionMethodEnum'
                    )
                  }}</span
                >
                <!-- {{ item.decotionMethod }} -->
                <span v-else>煎法</span>
                <!-- {{ item.decotionMethod }} -->
              </div>
              <div v-else class="combined-select-group-1">
                {{
                  useBaseDataStores.getEnumData(
                    item.decotionMethod,
                    'decotionMethodEnum'
                  )
                }}
              </div>

              <div
                click.stop
                class="combined-select-group-usage"
                v-if="item.uuid == isUsage"
              >
                <HerbUsagePopup
                  @onUsageClick="(result: any) => onUsageClick(result, item)"
                >
                </HerbUsagePopup>
              </div>
              <el-input-number
                v-model="item.dosage"
                style="width: 60px"
                v-if="visitStatus !== '2'"
                class="borderless-select right-select"
                placeholder=""
                :controls="false"
                @change="updateRow(item, item.uuid)"
                @focus="showKeyboard(item, item.uuid, 'dosage')"
                @click.stop
              >
                <template #suffix>
                  <span style="color: #999; font-size: 12px">{{
                    item.packUnitText
                  }}</span>
                </template>
              </el-input-number>
              <span v-else style="padding: 0 10px">
                {{ item.dosage }}
                <span style="color: #999; font-size: 12px">{{
                  item.packUnitText
                }}</span>
              </span>
              <div
                v-if="visitStatus !== '2'"
                class="delete-icon"
                @click="externalTreatment.tcmInfo.detailList.splice(index, 1)"
              >
                <img src="@/assets/icon/icon_off2_hover.svg" alt="" />
              </div>
                      <!-- 数字键盘 -->
            <div
              v-if="
                keyboardVisible &&
                currentEditNum === item.uuid &&
                currentEditField === 'dosage'
              "
              class="number-keyboard"
              @click.stop
            >
              <NumericKeyboardInt @input="inputNumber" @delete="deleteNumber" />
            </div>
            </div>
            <!-- 键盘 -->
            <SearchKeyboard
              :mode="keyboardMode"
              @input="(result: any) => onKeyboardInput_1(result, item)"
              @delete="(result: any) => onKeyboardDelete_1(result, item)"
              @clear="onKeyboardClear"
              @switch="onKeyboardSwitch"
              v-if="searchKeyboardVisible_1 && item.uuid == idDrug"
            />
            <!-- 搜索结果下拉列表 -->
            <div
              v-if="
                searchResults.length > 0 && item.drugName && item.uuid == idDrug
              "
              class="search-results"
              style="width: 700px"
              @click.stop
            >
              <SearchResultTable
                :searchResults="searchResults"
                :searchText="item.drugName"
                @select="(result: any) => selectSearchResult_1(result, item)"
              />
            </div>

    
          </div>
          <div class="combined-select-group" v-if="visitStatus !== '2'">
            <el-input
              ref="searchInputRef"
              v-model="searchText"
              style="width: 130px"
              class="borderless-select right-select"
              placeholder="选择药品"
              type="text"
              @input="handleSearch"
              @focus="showSearchKeyboard"
              @click.stop
            >
            </el-input>
          </div>
          <!-- 键盘 -->
          <!-- 键盘弹层用Teleport防止overflow裁剪 -->
          <div v-if="searchKeyboardVisible" ref="searchKeyboardRef">
            <SearchKeyboard
              :mode="keyboardMode"
              @input="onKeyboardInput"
              @delete="onKeyboardDelete"
              @clear="onKeyboardClear"
              @switch="onKeyboardSwitch"
            />
          </div>
          <!-- 搜索结果下拉列表 -->
          <div
            v-if="searchResults.length > 0 && searchText"
            class="search-results"
            @click.stop
          >
            <SearchResultTable
              :searchResults="searchResults"
              :searchText="searchText"
              @select="selectSearchResult"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import AutocompleteMulti from '@/components/AutocompleteMulti.vue';
import { CaretBottom, Star, Delete, Close } from '@element-plus/icons-vue';
import { getDrugRxList } from '@/api/formwork';
import stores from '@/store';
import { v4 as uuidv4 } from 'uuid';
const useBaseDataStores = stores.useBaseDataStore();
const props = defineProps({
  medicinalHerbData: {
    type: Object,
    default: () => {},
  },
  visitStatus: {
    type: String,
    default: '',
  },
  recomScene: {
    type: String,
    default: '',
  },
});
// 外治处方数据
const externalTreatment = ref<any>({});
const emit = defineEmits(['removeRow']);
const cycleUnitEnum = ref(useBaseDataStores.getEnumSelect('cycleUnitEnum'));
const FREQUENCY = ref<any[]>(useBaseDataStores.getDictsSelect('FREQUENCY'));
const acupointSideTypeEnum = ref<any[]>(
  useBaseDataStores.getEnumSelect('acupointSideTypeEnum')
);
const tcmDailyDosageEnum = ref<any[]>(
  useBaseDataStores.getEnumSelect('tcmDailyDosageEnum')
);
const currentEditNum = ref<number | null>(null);
const searchText = ref('');
const searchText_1 = ref('');
const isUsage = ref(null);
const searchKeyboardVisible = ref(false);
const searchKeyboardVisible_1 = ref(false);
// 键盘定位相关
const searchInputRef = ref<any | null>(null);
const searchKeyboardRef = ref<HTMLElement | null>(null);
const searchKeyboardStyle = ref<Record<string, string>>({});
const externalTreatment_1 = ref<any>({});
const idDrug = ref(null); //下拉搜索框
// 数字键盘相关
const keyboardVisible = ref(false);
const currentEditRow = ref<any | null>(null);
const currentEditField = ref<'dosage' | 'totalOutQty' | 'cycle' | null>(null);
const storageList = ref<any[]>(useBaseDataStores.Storage);
const detailList = ref<any[]>([]); //中西成药处方一 模板数据
// 用法弹窗相关
const showMedicationTabs = ref(false);
const showMedicationDosage = ref(false);
const searchResults = ref<Array<any>>([]);
const currentUsageRow = ref<any | null>(null);
// 计算总费用：∑(price*dosage) × (frequencyTimes*tcmDailyDosageNum)
const updateTcmTotalAmount = () => {
  const data = FREQUENCY.value.find(
    (item: any) =>
      item.frequencyCode === externalTreatment.value?.tcmInfo?.frequencyCode
  );
  if (data) {
    externalTreatment.value.tcmInfo.frequencyTimes = Number(
      data.frequencyTimes || 0
    );
    const match = cycleUnitEnum.value.find(
      (item: any) => item.value === data.cycleUnit
    );
    externalTreatment.value.tcmInfo.cycleUnitCode = data.cycleUnit;
    externalTreatment.value.tcmInfo.cycleUnitText = match ? match.text : '';
  } else {
    externalTreatment.value.tcmInfo.frequencyTimes = 0;
  }
  // 匹配 cycleUnitEnum
  const data1 = tcmDailyDosageEnum.value.find(
    (item: any) => item.value === externalTreatment.value?.tcmInfo?.dailyDosage
  );
  if (data1) {
    externalTreatment.value.tcmInfo.tcmDailyDosageNum = data1.dosage;
  } else {
    externalTreatment.value.tcmInfo.tcmDailyDosageNum = 0;
  }
  const dailyNum =
    Number(externalTreatment.value?.tcmInfo?.tcmDailyDosageNum) || 0;
  const freqTimes =
    Number(externalTreatment.value?.tcmInfo?.frequencyTimes) || 0;
  const multiplier = freqTimes * dailyNum;

  const list = externalTreatment.value?.tcmInfo?.detailList || [];
  let baseSumCents = 0;
  for (const it of list) {
    const priceCents = Number((it as any).price) || 0; // 价格单位：分
    const dosage = Number((it as any).dosage) || 0;
    baseSumCents += priceCents * dosage;
  }
  externalTreatment.value.totalAmount = baseSumCents * (multiplier || 0);
};
watch(
  () => props.medicinalHerbData,
  (newVal) => {
    // 不要直接修改 props，先做深拷贝，避免父子相互触发导致多次执行
    const cloned: any = newVal ? JSON.parse(JSON.stringify(newVal)) : {};
    const srcList = Array.isArray(cloned?.tcmInfo?.detailList)
      ? cloned.tcmInfo.detailList
      : [];
    if (!cloned.tcmInfo) cloned.tcmInfo = {};
    cloned.tcmInfo.detailList = srcList.map((item: any) => ({
      ...item,
      uuid: item?.uuid || uuidv4(),
    }));
    externalTreatment.value = cloned;
    //console.log('传入的处方数据:', newVal);
    updateTcmTotalAmount();
  },
  { immediate: true }
);
// 监听药品明细变化（dosage/增删改）
watch(
  () => externalTreatment.value?.tcmInfo?.detailList,
  () => {
    updateTcmTotalAmount();
  },
  { deep: true }
);

const onUsageCode = (row: any) => {
  if (currentUsageRow.value === row && showMedicationTabs.value) {
    // 再次点击同一行则关闭
    showMedicationTabs.value = false;
    currentUsageRow.value = null;
  } else {
    showMedicationTabs.value = true;
    showMedicationDosage.value = false;
    currentUsageRow.value = row;
    keyboardVisible.value = false;
  }
  keyboardVisible.value = false;
};
const onUsageDosage = (row: any) => {
  if (currentUsageRow.value === row && showMedicationTabs.value) {
    // 再次点击同一行则关闭
    showMedicationTabs.value = false;
    showMedicationTabs.value = false;
    currentUsageRow.value = null;
  } else {
    showMedicationTabs.value = false;
    showMedicationDosage.value = true;
    currentUsageRow.value = row;
    keyboardVisible.value = false;
  }
};

const updateRow = (row: any, index: number) => {
  // 当编辑现有行时，自动保存更改
  //console.log('更新行数据:', row);
  updateTcmTotalAmount();
};

// 数字键盘相关方法
const showKeyboard = (
  row: any,
  index: number,
  field: 'dosage' | 'totalOutQty' | 'cycle'
) => {
  //console.log(index);

  currentEditRow.value = row;
  currentEditNum.value = index;
  currentEditField.value = field;
  keyboardVisible.value = true;
  isUsage.value = null;
  showMedicationTabs.value = false;
  showMedicationTabs.value = false;
};
const onSelectItem = (item: any) => {
  //console.log(item);

  externalTreatment.value.tcmInfo.singleDosage = item;
  showMedicationDosage.value = false;
};
const handleGlobalClickUsage = (event: Event) => {
  // 如果点击的是 MedicationTabs 内部，不关闭
  const target = event.target as HTMLElement;
  if (target.closest('.herb-usage-popup')) return;
  // isUsage.value = false;
};
// 煎法点击其他位置
// const handleGlobalClick = (event: Event) => {
//   showMedicationTabs.value = false;
//   searchKeyboardVisible.value = false;
//   searchKeyboardVisible_1.value = false;
//   showMedicationDosage.value = false;
//   currentUsageRow.value = null;
//   searchResults.value = [];
//   searchText.value = '';
//   isUsage.value = null;
//   idDrug.value = null;
// };
const hideKeyboardClick = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.herb-usage-popup-1')) {
      return;
    }
  }
  showMedicationDosage.value = false;
};
// 点击其他地方关闭 MedicationTabs
const handleGlobalClick = (event: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.medication-tabs')) {
      return;
    }
  }
  showMedicationTabs.value = false;
};
const selectedUsage = (selectedItems: any, usageName: string) => {
  //console.log(selectedItems, usageName);
  externalTreatment.value.tcmInfo.usageCodeText = usageName;
  externalTreatment.value.tcmInfo.usageCode = selectedItems.value[0];
  showMedicationTabs.value = false;
};
const removeRow_1 = (group: any) => {
  if (group) {
    emit('removeRow', group);
  }
};

const inputNumber = (num: string) => {
  if (!currentEditRow.value || !currentEditField.value) {
    return;
  }

  const field = currentEditField.value;
  let currentValue = currentEditRow.value[field];

  // 处理小数点输入
  if (num === '.') {
    // 如果当前值已经是数字且不包含小数点，才允许添加小数点
    if (
      typeof currentValue === 'number' &&
      !currentValue.toString().includes('.')
    ) {
      currentEditRow.value[field] = currentValue.toString() + '.';
    }
    // 如果当前值是undefined/null，设置为"0."
    else if (currentValue === undefined || currentValue === null) {
      currentEditRow.value[field] = '0.';
    }
    updateTcmTotalAmount();
    return;
  }

  // 处理数字输入
  if (currentValue === undefined || currentValue === null) {
    currentEditRow.value[field] = num;
  } else {
    const currentStr = currentValue.toString();

    // 如果当前值包含小数点（小数模式）
    if (currentStr.includes('.')) {
      const [integerPart, decimalPart] = currentStr.split('.');

      // 防止小数部分过长（例如限制2位小数）
      if (decimalPart.length < 2) {
        currentEditRow.value[field] = currentStr + num;
      }
    }
    // 整数模式
    else {
      const newValue = currentStr === '0' ? num : currentStr + num;
      currentEditRow.value[field] = newValue;
    }
  }

  // 转换为数字验证范围
  const numericValue = Number(currentEditRow.value[field]);
  const maxValue = field === 'cycle' ? 999 : 999; // 可根据不同字段设置不同最大值

  if (numericValue <= maxValue) {
    updateTcmTotalAmount();
  } else {
    // 回退到之前的值
    currentEditRow.value[field] = currentValue;
  }
};

const deleteNumber = () => {
  if (!currentEditRow.value || !currentEditField.value) return;
  const currentValue = currentEditRow.value[currentEditField.value].toString();
  const newValue = currentValue.slice(0, -1);
  currentEditRow.value[currentEditField.value] =
    newValue === '' ? null : parseInt(newValue);
  // const currentValue = currentEditRow.value[currentEditField.value].toString();
  // const newValue = parseInt(currentValue.slice(0, -1)) || 1;
  // currentEditRow.value[currentEditField.value] = newValue;
  if (currentEditField.value === 'dosage') updateTcmTotalAmount();
};
const onFrequency = (row: any) => {
  const selectedFrequency = FREQUENCY.value?.find(
    (freq) => freq.frequencyCode === row.frequencyCode
  );
  if (selectedFrequency) {
    row.cycleUnit = selectedFrequency.cycleUnit;
    row.cycleUnitText = useBaseDataStores.getEnumData(
      selectedFrequency.cycleUnit,
      'cycleUnitEnum'
    );
  }
};
// 搜索方法
const handleSearch = async (value: string) => {
  //console.log('搜索内容:', value);
  searchKeyboardVisible_1.value = false;
  // 模拟搜索结果数据
  if (value && value.trim()) {
    // 根据图片显示的结果
    const result = await getDrugRxList({
      drugName: value,
      drugCategory: '2', // 中药
      storageId: externalTreatment.value.storageId,
      recomScene: props.recomScene,
    });
    searchResults.value =
      result?.data.map((item: any) => ({
        ...item,
        drugCategoryName: useBaseDataStores.getEnumData(
          item.drugCategory,
          'drugCategoryEnum'
        ),
     specification:
      item.drugCategory == 3
        ? `${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`
        : `${item.drugDosage}${item.drugDosageUnitText}*${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`,
        usageCode: item?.usageList?.[0]?.usageCode || '',
        usageCodeText: '',
        mfrName: useBaseDataStores.getMfrName(item.mfrId),
        priceNum: (item.price / 100).toFixed(2),
        frequencyCode: '',
        frequencyCodeText: '',
        dosage: null,
        dosageUnit: '',
        dosageUnitText: '',
        cycle: '',
        cycleUnit: '',
        cycleUnitText: '',
        totalOutQty: '',
        totalOutQtyUnit: '',
        totalOutQtyUnitText: '',
      })) || [];
  } else {
    searchResults.value = [];
  }
};
// 用法弹框事件
const onUsageClick = (val: any, item: any) => {
  isUsage.value = null;

  item.decotionMethod = val.value;
  //console.log(val, item);
};

// 监听 tcmInfo.frequencyCode 变化
watch(
  () => externalTreatment.value?.tcmInfo?.frequencyCode,
  (newVal) => {
    // 从 FREQUENCY 匹配 frequencyTimes
    updateTcmTotalAmount();
  }
);
// externalTreatment.tcmInfo.dailyDosage
watch(
  () => externalTreatment.value.tcmInfo.dailyDosage,
  (newVal) => {
    // 频次改变后，若收费类型为按次数计费(1)，同步更新数量
    // updateQuantityByChargeType();
    updateTcmTotalAmount();
  }
);
// 搜索方法
const handleSearch_1 = async (value: string) => {
  //console.log('搜索内容:', value);
  searchKeyboardVisible.value = false;
  // 模拟搜索结果数据
  if (value && value.trim()) {
    // 根据图片显示的结果
    const result = await getDrugRxList({ drugName: value, drugCategory: '2' });
    searchResults.value =
      result?.data.map((item: any) => ({
        ...item,
        drugCategoryName: useBaseDataStores.getEnumData(
          item.drugCategory,
          'drugCategoryEnum'
        ),
      specification:
      item.drugCategory == 3
        ? `${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`
        : `${item.drugDosage}${item.drugDosageUnitText}*${item.minPackQty}${item.minPackUnitText}/${item.packUnitText}`,
        usageCode: item?.usageList?.[0]?.usageCode || '',
        usageCodeText: '',
        frequencyCode: '',
        frequencyCodeText: '',
        dosage: null,
        dosageUnit: '',
        dosageUnitText: '',
        cycle: '',
        cycleUnit: '',
        cycleUnitText: '',
        totalOutQty: '',
        totalOutQtyUnit: '',
        totalOutQtyUnitText: '',
      })) || [];
  } else {
    searchResults.value = [];
  }
};
const keyboardMode = ref<'english' | 'chinese'>('english');
// 用法弹框
const onUsage = (val: any) => {
  searchKeyboardVisible_1.value = false;
  isUsage.value = val;
  //console.log('用法弹窗');
};
const calcInputWidth = (val: string) => {
  const base = 80; // 最小宽度
  const max = 200; // 最大宽度
  const len = val ? val.length : 0;
  return `${Math.min(base + len * 8, max)}px`;
};
// 搜索键盘事件方法
const onKeyboardInput = (char: string) => {
  searchText.value += char;
  handleSearch(searchText.value);
};
// 搜索键盘事件方法
const onKeyboardInput_1 = (char: string, data: any) => {
  if (!data.drugName) {
    data.drugName = '';
  }
  data.drugName += char;
  handleSearch_1(data.drugName);
};
const onKeyboardDelete = () => {
  if (searchText.value.length > 0) {
    searchText.value = searchText.value.slice(0, -1);
    handleSearch(searchText.value);
  }
};
const onKeyboardDelete_1 = (char: string, data: any) => {
  if (data.drugName.length > 0) {
    data.drugName = data.drugName.slice(0, -1);
    handleSearch(data.drugName);
  }
};
const onKeyboardClear = () => {
  searchText.value = '';
  searchResults.value = [];
};
const onKeyboardSwitch = () => {
  if (keyboardMode.value === 'english') {
    keyboardMode.value = 'chinese';
  } else if (keyboardMode.value === 'chinese') {
    keyboardMode.value = 'english';
  } else {
    keyboardMode.value = 'english';
  }
};
const hideSearchKeyboard = (event?: Event) => {
  // 如果点击的是键盘内部或搜索结果，不隐藏
  if (event && event.target) {
    const target = event.target as Element;
    if (
      target.closest('.search-keyboard') ||
      target.closest('.search-results') ||
      target.closest('.search-input') ||
      target.closest('.elInputs')
    ) {
      return;
    }
  }

  searchKeyboardVisible.value = false;
  searchResults.value = [];
  // // 移除键盘事件监听器
  // document.removeEventListener('keydown', handleKeyboardShortcut);
  // window.removeEventListener('resize', nextTickPositionKeyboard);
  // window.removeEventListener('scroll', nextTickPositionKeyboard, true);
  if (event && event.target) {
    const target = event.target as Element;
    if (
      target.closest('.search-keyboard') ||
      target.closest('.search-results') ||
      target.closest('.search-input') ||
      target.closest('.elInput2')
    ) {
      return;
    }
  }
  searchKeyboardVisible_1.value = false;
  // 移除键盘事件监听器
  document.removeEventListener('keydown', handleKeyboardShortcut);
};
// 处理键盘快捷键
const handleKeyboardShortcut = (event: KeyboardEvent) => {
  // Ctrl + Shift + T 切换键盘模式
  if (event.ctrlKey && event.shiftKey && event.key === 'T') {
    event.preventDefault();
    onKeyboardSwitch();
  }
  // Esc 键隐藏键盘
  else if (event.key === 'Escape') {
    event.preventDefault();
    hideSearchKeyboard();
  }
};
// 搜索键盘相关方法
const showSearchKeyboard = () => {
  searchKeyboardVisible.value = true;
  searchKeyboardVisible_1.value = false;
  // 定位键盘到输入框上方
  nextTickPositionKeyboard();
  // // 添加监听
  document.addEventListener('keydown', handleKeyboardShortcut);
  // window.addEventListener('resize', nextTickPositionKeyboard);
  // window.addEventListener('scroll', nextTickPositionKeyboard, true);
};
// 搜索键盘相关方法
const showSearchKeyboard_1 = (id: any) => {
  searchKeyboardVisible.value = false;
  searchKeyboardVisible_1.value = true;

  idDrug.value = id;
  // 添加键盘事件监听器
  document.addEventListener('keydown', handleKeyboardShortcut);
};
const selectSearchResult = (result: any) => {
  // 选择搜索结果
  //console.log('选择了:', result);
  result.usageCodeText = useBaseDataStores.getDictsUSAGEData(
    result.usageCode,
    'USAGE'
  );
  result.uuid = uuidv4();
  result.remark = result.instrs;
  externalTreatment.value.tcmInfo.detailList.push(result);
  searchKeyboardVisible_1.value = false;
  searchKeyboardVisible.value = false;
  idDrug.value = null;
  searchResults.value = [];
  searchText.value = '';
  updateTcmTotalAmount();
};
const selectSearchResult_1 = (result: any, drug: any) => {
  //console.log('选择了:', result);
  //console.log('drugName:', drug);
  result.usageCodeText = useBaseDataStores.getDictsUSAGEData(
    result.usageCode,
    'USAGE'
  );
  result.remark = result.instrs;
  Object.assign(drug, result);
  searchKeyboardVisible_1.value = false;
  idDrug.value = null;
  searchResults.value = [];
  updateTcmTotalAmount();
};
const hideKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.number-keyboard')) {
      return;
    }
  }

  keyboardVisible.value = false;
  currentEditRow.value = null;
  currentEditField.value = null;
};

// 统一的全局点击处理函数（之前 onMounted/onUnmounted 内部各自声明，导致 removeEventListener 无法正确移除）
const globalClickHandler = (event: Event) => {
  hideKeyboard(event);
  handleGlobalClickUsage(event);
  hideSearchKeyboard(event);
  handleGlobalClick(event);
  hideKeyboardClick(event);
};

onMounted(() => {
  document.addEventListener('mousedown', globalClickHandler);
});

onUnmounted(() => {
  document.removeEventListener('mousedown', globalClickHandler);
  window.removeEventListener('resize', nextTickPositionKeyboard);
  window.removeEventListener('scroll', nextTickPositionKeyboard, true);
});
defineExpose({
  externalTreatment,
});

// 计算键盘位置（固定定位到视口），优先显示在输入框上方，不够则显示在下方；超出右侧自动左移
const positionKeyboard = () => {
  const inputEl = (searchInputRef.value as any)?.$el || searchInputRef.value;
  const popupEl = searchKeyboardRef.value;
  if (!inputEl || !popupEl) return;

  const rect = inputEl.getBoundingClientRect();
  const kbRect = popupEl.getBoundingClientRect();
  const margin = 8;

  let top = rect.top - kbRect.height - margin; // 默认上方
  let left = rect.left; // 左对齐

  if (top < 0) {
    // 上方放不下，则放到下方
    top = rect.bottom + margin;
  }

  const vw = window.innerWidth;
  if (left + kbRect.width > vw - margin) {
    left = Math.max(margin, vw - kbRect.width - margin);
  }
  if (left < margin) left = margin;

  searchKeyboardStyle.value = {
    position: 'fixed',
    top: `${Math.round(top)}px`,
    left: `${Math.round(left)}px`,
    zIndex: '9999',
  };
};

const nextTickPositionKeyboard = () => {
  // 等待一帧，确保 Teleport DOM 就绪
  requestAnimationFrame(() => positionKeyboard());
};

// 备注建议：仅取 rxType === 3 的项
const querySearchAsync = (queryString: string, cb: any) => {
  const data = useBaseDataStores.getDictsSelect('REMARK') || [];
  const filtered = (Array.isArray(data) ? data : []).filter(
    (item: any) => item?.rxType === 3 || item?.rxType === '3'
  );
  const results = filtered.map((item: any) => ({
    value: item.remarkText,
    ...item,
  }));
  cb(results);
};
</script>

<style lang="scss" scoped>
.search-keyboard-popup {
  position: fixed;
  z-index: 9999;
  /* 其余样式可继承 .number-keyboard 或自定义 */
}
::v-deep(.el-input__wrapper) {
  padding-left: 5px !important;
  padding-right: 5px !important;
}

.external-treatment-container {
  background-color: #fff;
  margin-bottom: 10px;
  .external-treatment-prescription {
    border-radius: 8px;
  }
  .custom-table {
    width: 100%;
    border: 1px solid #e7e7e7;
    background: #ffffff;

    .table-header {
      display: flex;
      padding: 12px 16px;
      background-color: #f8f8f8;
      border-bottom: 1px solid #e4e7ed;
      align-items: center;
      border-radius: 8px;

      .header-cell {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #333333;
        cursor: pointer;
        .delete-icon {
          color: #c0c4cc;
          cursor: pointer;

          &:hover {
            color: #f56c6c;
          }
        }
      }
    }

    .prescription-form-row {
      display: flex;
      align-items: center;
      padding: 16px;
      gap: 12px;
      border-bottom: 1px solid #f0f0f0;

      .form-item {
        display: flex;
        align-items: center;
        position: relative;
        .unit-text {
          font-size: 14px;
          color: #333;
          margin-left: 4px;
        }
      }
    }

    .acupoint-selection-area {
      padding: 16px;

      .acupoint-row {
        display: flex;
        align-items: center;
        gap: 30px 50px;
        flex-wrap: wrap;
        position: relative;

        .combined-select-group {
          display: flex;
          align-items: center;
          box-shadow: 0 0 0 1px #dcdfe6;
          border-radius: 5px;
          // position: relative;

          &:focus-within {
            box-shadow: 0 0 0 1px #409eff !important;
          }

          &:hover {
            box-shadow: 0 0 0 1px #c0c4cc !important;
          }

          .left-select {
            height: 100%;
            :deep(.el-input__wrapper) {
              box-shadow: none !important;
              height: 38px;
              border-radius: 5px !important;
              border-right: 1px solid #dbdbdb;
            }

            :deep(.el-input__wrapper:focus) {
              box-shadow: none !important;
              border: none !important;
            }

            :deep(.el-input__wrapper:hover) {
              box-shadow: none !important;
              border: none;
              border-radius: 5px !important;
              border-right: 1px solid #dbdbdb;
            }
          }

          .right-select {
            height: 100%;
            :deep(.el-input__wrapper) {
              border: none !important;
              box-shadow: none !important;
              height: 38px;
            }

            :deep(.el-input__wrapper:focus) {
              box-shadow: none !important;
              border: none !important;
            }

            :deep(.el-input__wrapper:hover) {
              box-shadow: none !important;
              border: none !important;
            }
          }

          .select-divider {
            width: 1px;
            height: 24px;
            background-color: #e4e7ed;
            flex-shrink: 0;
            margin: 0 2px;
          }

          &:hover {
            border-color: #c0c4cc;
          }

          &:focus-within {
            border-color: #409eff;
            /* 只显示右边线的方法 */
            box-shadow: inset -1px 0 0 0 rgba(64, 158, 255, 0.3);
          }
        }

        .acupoint-group {
          display: flex;
          align-items: center;
        }

        .remove-button {
          display: flex;
          align-items: center;
          margin-left: auto;
          margin-right: 12px;

          .remove-btn {
            padding: 4px;
            color: #c0c4cc;

            &:hover {
              color: #f56c6c;
            }
          }
        }

        .acupoint-selector {
          display: flex;
          align-items: center;
          gap: 8px;
          background: #ffffff;
          padding: 8px 12px;
          border-radius: 6px;
          border: 1px solid #e4e7ed;
          cursor: pointer;
          transition: all 0.2s;
          height: 51px;
          &:hover {
            background: #e9ecef;
            border-color: #409eff;
          }

          .selector-text {
            font-size: 14px;
            color: #666;
          }

          .selector-icon {
            color: #f56c6c;
          }
        }
      }
    }
  }

  // 无边框选择框样式
  :deep(.borderless-select) {
    .el-input__wrapper {
      box-shadow: none;
      border-radius: 6px;
      height: 51px !important;
    }

    &:hover .el-input__wrapper {
      border-color: #c0c4cc;
    }

    &.is-focus .el-input__wrapper {
      border-color: #409eff;
    }
  }

  // 无边框输入框样式
  :deep(.borderless-input) {
    .el-input__wrapper {
      border: 1px solid #dcdfe6;
      box-shadow: none;
      border-radius: 6px;
    }

    &:hover .el-input__wrapper {
      border-color: #c0c4cc;
    }

    &.is-focus .el-input__wrapper {
      border-color: #409eff;
    }
  }
}
</style>
<style lang="scss" scoped>
.left-select {
  .el-input__wrapper {
    height: 51px;
    background-color: rgba(220, 220, 220, 0.1) !important;
    box-shadow: inset -1px 0 0 0 #dcdfe6;
  }
  .el-input__wrapper:hover {
    box-shadow: inset -1px 0 0 0 #dcdfe6 !important;
  }
  .el-input__wrapper:focus-within {
    border-color: #409eff;
    box-shadow: inset -1px 0 0 0 rgba(64, 158, 255, 0.3);
  }
}
.right-select {
  .el-input__wrapper {
    height: 51px;
    // box-shadow: none !important;
  }
  .el-input__wrapper:hover {
    box-shadow: none !important;
  }
  .el-input__wrapper:focus-within {
    box-shadow: none !important;
    border: none !important;
  }
}
.borderless-select_1 {
  .el-select__wrapper {
    height: 51px !important;
  }
}
// 搜索结果样式
.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 9998;

  // 重写搜索结果中的表头样式，确保与内容对齐
  .table-header {
    .header-cell {
      text-align: left !important;
      justify-content: flex-start !important;
    }
  }

  .search-result-item {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f5f7fa;
    cursor: pointer;
    text-align: left;
    transition: background-color 0.2s;
    height: 48px; // 设置固定高度

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background-color: #f0f9ff;
    }

    // 清除子元素样式，使用内联样式控制
    .result-name,
    .result-category,
    .result-spec,
    .result-price {
      display: flex;
      align-items: center;
      height: 100%;
      font-size: 14px;
      color: #333;
    }

    .result-category,
    .result-spec {
      font-size: 12px;
      color: #666;
    }

    .result-price {
      font-weight: 600;
    }
  }
}
.combined-select-group-1 {
  position: absolute;
  top: 33px;
  left: 6px;
  color: #999;
  font-size: 12px;
  height: 17px;
  background: #eaeaea;
  cursor: pointer;
  border-radius: 2px;
  min-width: 25px;
  padding: 0 3px;
  line-height: 17px;
}
.combined-select-group-usage {
  position: absolute;
  top: 52px;
  left: 20px;
  color: #999;
  font-size: 12px;
  cursor: pointer;
  z-index: 9999;
}
// 数字键盘样式
.number-keyboard {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 9999 !important;
  border: 1px solid #e4e7ed;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25); // 增强阴影效果
  margin-top: 4px;
  transform: translateZ(0); // 硬件加速，确保显示在最顶层

  .keyboard-row {
    display: flex;
    gap: 4px;
    margin-bottom: 4px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .key-btn {
    width: 50px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background: #f8f9fa;
    color: #333;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: #e9ecef;
      border-color: #409eff;
    }

    &:active {
      background: #dee2e6;
      transform: scale(0.95);
    }

    &.delete-btn {
      width: 104px; // 退格键宽度是两个按钮+间距
      background: #f56c6c;
      color: white;
      font-size: 14px;

      &:hover {
        background: #f78989;
      }
    }
  }
}
.delete-icon {
  position: absolute;
  top: -3px;
  right: 0;
}
</style>
